import re
from datetime import datetime
import hashlib

class Invoice:
    def __init__(self, invoice_type=-1, amount=0.0, code="", invoice_date="", tax_rate="", tax_amount=0.0, txt_amount=0.0, features=None):
        if features is None:
            features = set()
        self.invoice_type = invoice_type
        self.amount = amount
        self.code = code
        self.tax_code = code
        self.invoice_date = invoice_date
        self.check_id = ""
        self.tax_rate = tax_rate
        self.tax_amount = tax_amount
        self.txt_amount = txt_amount
        self.features = features
        self.page_count = 1

    def calculate_check_id(self):
        # 合并 invoice_type, invoice_date 和 code   去掉其他的就是怕调改逻辑后md5值变化
        combined_string = f"{self.invoice_date}{self.code}{self.amount}"
        # 计算 MD5 值
        md5_hash = hashlib.md5(combined_string.encode('utf-8')).hexdigest()
        return md5_hash

    def to_dict(self):
        type_mapping = {
            0: '数电发票',
            1: '电子发票',
            2: '机打发票',
            11: '火车电子发票'
        }
        invoice_type_description = type_mapping.get(self.invoice_type, '未知类型')
        if self.invoice_type == 2 or self.invoice_type == 1:
            self.tax_code = self.code.split("-")[0]
        if self.invoice_type == 11:
            self.tax_amount = round(self.amount/1.09*0.09, 2)
        return {
            'check_id': self.calculate_check_id(),
            'type': invoice_type_description,
            'tax_code': self.tax_code,
            'invoice_date': self.invoice_date,
            'amount': self.amount,
            'tax_rate': self.tax_rate,
            'tax_amount': self.tax_amount,
            'txt_amount': self.txt_amount,
            'code': self.code,
            'features': str(self.features),
            'page_count': self.page_count,
            'valid': self.invoice_type != -1
        }

    def valid(self):
        return self.invoice_type != -1


